{% extends 'IcsocUIBundle::page.html.twig' %}

{% block stylesheet %}
    {{ parent() }}
    {% stylesheets
    'bundles/icsocivr/css/zTreeStyle.css'
    '@jquery_ui_css'
    '@jqgird_css'
    '@chosen_css'
    '@gritter_css'
    filter="cssrewrite"  filter='uglifycss'
    %}
    <!--suppress ALL -->
    <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12 col-sm-12">
                <form class="form-inline" role="form">
                    <button id="save-ivr" class="btn btn-primary btn-sm" type="button">
                        <i class="ace-icon fa fa-save"></i> {{ 'Save Ivr'|trans }}
                    </button>
                    <button id="back" class="btn btn-sm" type="button">
                        <i class="ace-icon fa fa-reply"></i> {{ 'Back'|trans }}
                    </button>
                    <div class="form-group">
                        <label for="ivr_name">{{ 'Ivr name'|trans }}</label>
                        <input type="text" class="form-control" id="ivr_name" placeholder="{{ 'Ivr name'|trans }}" value="{{ ivr_name|default('Default IVR')|trans }}">
                    </div>
                    <div class="form-group" id="copy_ivr_div" style="display: none">
                        <label for="copy_ivr_to">{{ 'Copy Ivr To'|trans }}</label>
                        <input type="text" class="form-control" id="ivr_name_copy" placeholder="{{ 'Ivr name'|trans }}" value="{{ ivr_name|default('Default IVR')|trans }} - {{ 'duplicate'|trans }}">
                        <button id="copy_ivr" class="btn btn-primary btn-sm" type="button">
                            <i class="ace-icon fa fa-save"></i> {{ 'Copy Ivr'|trans }}
                        </button>
                    </div>
                    <div class="form-group" id="remark_div" style="display: none">
                        <button id="remark" class="btn btn-primary btn-sm" type="button">
                            <i class="ace-icon fa fa-plus"></i> {{ 'Add Remark'|trans }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-5 col-sm-5 widget-container-col">
                <div id="panel-ivr" class="widget-box" style="opacity: 1;">
                    <div class="widget-header widget-header-small">
                        <h5 class="widget-title">{{ 'IVR Structure'|trans }}</h5>
                    </div>
                    <div class="widget-body" id="widget-body" style="overflow-y:auto;">
                        <div class="widget-main">
                            <ul id="tree" class="ztree"></ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-7 col-sm-7 widget-container-col">
                <div id="panel-attr" class="widget-box" style="opacity: 1;">
                    <div class="widget-header widget-header-small">
                        <h5 class="widget-title">{{ 'Node Attribute'|trans }}</h5>
                    </div>
                    <div class="widget-body" id="nodeAttr_div" style="overflow-y:scroll;">
                        <div class="widget-main">
                            <div id="nodeAttr"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="dialog-confirm" class="hide row">
        <div class="row">
            <label class="col-xs-10 col-sm-2" style="text-align: right">{{ 'remark'|trans }}</label>
            <textarea id="remark_val" class="col-xs-10 col-sm-8" cols="40" rows="3"></textarea>
        </div>
        <div class="hide row" id="remark-confirm" style="text-align: center;margin-top: 2px">
            <span style="color: red">备注不能为空</span>
        </div>
        <div class="row" style="text-align: center;margin-top: 2px">
            <button id="remark-btns" type="button" class="btn btn-success btn-sm" data-loading-text="Loading...">
                {{ 'Save'|trans }}
            </button>
        </div>
    </div>
{% endblock %}

{% block javascript %}
    {{ parent() }}
    {% javascripts
    'bundles/icsocivr/js/jquery.ztree.all-3.5.min.js'
    '@jqgird_js'
    '@jquery_ui_js'
    '@chosen_js'
    '@bootbox_js'
    '@gritter_js'
    '@common_js'
    '@jqvalidate_js'
    %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
    <script type="application/javascript">
        var selectedNode = null;
        var allNodes = {};
        var allSelectNodes = {};
        var $red = {'color': 'red'};
        var $green = {'color': 'green'};
        var ivr_id = '{{ ivr_id|default(0) }}';
        var nodeId = [];
        var delMsg = '';//删除节点提示信息
        var delTid = '';//删除节点Id
        var sound_list = {'sound':0,'navigation_sound': 0,'error_key_sound':0,'none_key_sound':0};


        //数字变量
        var variableName = {
            'system':{'vcc_id':'vcc_id','vcc_code':'vcc_code','caller':'caller','server_num':'server_num','server_400':'server_400','call_id':'call_id','call_time':'call_time','caller_areacode':'caller_areacode','caller_areaname':'caller_areaname','caller_type':'caller_type','caller_vendor':'caller_vendor'},
            'custom':{}
        };
        var variableIndex = 1;
        var variableNode = '';//当前节点的父节点，获取变量的时候用到
        var oldJumpNode = '';//当前节点之前设置的跳转节点
        var allParentNode = [];//当前节点所有的父节点
        var defaultNewNodes = {
            node_2: {name:"{{ 'Play Sound'|trans }}",type:2,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/bofangyuyin.png') }}"},
            node_3: {name:"{{ 'Navigation'|trans }}",type:3,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/anjiandaohang.png') }}",open:true,children:[
                {name:"{{ 'F' }}",type:30,isDel:false,icon:"{{ asset('bundles/icsocivr/images/anjian.png') }}"},
            ]},
            node_5: {name:"{{ 'Go To Queue'|trans }}",type:5,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/zhuanjinengzu.png') }}",open:true,children:[
                {name:"{{ 'Queue Fail'|trans }}",condition:"queue_fail",type:50,icon:"{{ asset('bundles/icsocivr/images/zhuanjieshibai.png') }}"}
            ]},
            node_6: {name:"{{ 'Leave Message'|trans }}",type:6,isRealNode:true,record_id:0,playfile:'',msgnum:'',icon:"{{ asset('bundles/icsocivr/images/liuyan.png') }}"},
            node_7: {name:"{{ 'Hangup'|trans }}",type:7,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/guaji.png') }}"},
            node_8: {name:"{{ 'Receive Keys'|trans }}",type:8,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/shouhao.png') }}",open:true,children:[
                {name:"{{ 'Keys success'|trans }}",condition:"keys_success",type:80,icon:'{{ asset('bundles/icsocivr/images/shouhaochenggong.png') }}'},
                {name:"{{ 'Keys timeout'|trans }}",condition:"keys_timeout",type:80,icon:'{{ asset('bundles/icsocivr/images/shouhaochaoshi.png') }}'}
            ]},
            node_9: {name:"{{ 'Http Api'|trans }}",type:9,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/httpjiekou.png') }}",open:true,children:[
                {name:"{{ 'Return success'|trans }}",isDel:false,condition:"return_success",type:90,icon:'{{ asset('bundles/icsocivr/images/shouhaochenggong.png') }}'},
                {name:"{{ 'Return failure'|trans }}",isDel:false,condition:"return_failure",type:90,icon:'{{ asset('bundles/icsocivr/images/fanhuishibai.png') }}'}
            ]},
            node_10: {name:"{{ 'Call Memory'|trans }}",type:10,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/laidianjiyi.png') }}",open:true,children:[
                {name:"{{ 'Return success'|trans }}",isDel:false,condition:"return_success",type:100,icon:'{{ asset('bundles/icsocivr/images/shouhaochenggong.png') }}'},
                {name:"{{ 'Return failure'|trans }}",isDel:false,condition:"return_failure",type:100,icon:'{{ asset('bundles/icsocivr/images/fanhuishibai.png') }}'}
            ]},
            node_11: {name:"{{ 'Go To Phone'|trans }}",type:11,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/zhuandianhua.png') }}"},
            node_12: {name:"{{ 'Go To Agent'|trans }}",type:12,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/zhuanzuoxi.png') }}"},
            node_14: {name:"{{ 'Go To Ivr'|trans }}",type:14,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/zhuanjinengzu.png') }}"},
            node_13: {name:"{{ 'Judge'|trans }}",type:13,isRealNode:true,icon:"{{ asset('bundles/icsocivr/images/panduan.png') }}",open:true,children:[
                {name:"{{ 'F' }}",isDel:false,condition:"judge_fail",type:130,icon:"{{ asset('bundles/icsocivr/images/fanhuishibai.png') }}"}
            ]}
        };
        $(document).ready(function() {
            var $documentHeight = $(document).height();
            $('#panel-ivr').height($documentHeight - 50);
            $('#panel-attr').height($documentHeight - 50);
            $('#panel-attr').height($documentHeight - 50);
            $('#widget-body').height($documentHeight - 100);
            $('#nodeAttr_div').height($documentHeight - 100);
            //设置ivr名称
            $('#ivr_name').on('keyup', function () {
                var treeObj = $.fn.zTree.getZTreeObj("tree")
                var rootNode = treeObj.getNodeByTId('tree_1');
                rootNode.name = $(this).val();
                treeObj.updateNode(rootNode);
            });
            //保存IVR
            $('#save-ivr').on('click', function () {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var unsavedAttrNode = treeObj.getNodeByParam('nodeStatus', false);
                if (unsavedAttrNode != null) {
                    gritterAlert("{{ 'Alert'|trans }}", '【'+unsavedAttrNode.name + "】{{ 'is not saved'|trans }}", 'error');
                    return false;
                }
                var treeNodeArray = treeObj.transformToArray(treeObj.getNodes());
                var treeNodesString = JSON.stringify(treeNodeArray);
                var ivr_name = $('#ivr_name').val();
                if (!ivr_name) {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Input ivr name'|trans }}", 'error');
                    return false;
                }
                $.ajax({
                    url: "{{ path('icsoc_ivr_save') }}",
                    dataType: 'json',
                    data: {ivrString: treeNodesString, ivr_name:ivr_name, ivr_id: ivr_id},
                    type: 'post',
                    success: function(response) {
                        if (response.code == 200) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Ivr save success'|trans }}", 'success');
                            ivr_id = response.ivr_id;
                            $('#copy_ivr_div').css('display', 'inline-block');//显示复制IVR功能
                            $('#ivr_name_copy').val(ivr_name + "-{{ 'duplicate'|trans }}");
                            $('#remark_div').css('display', 'inline-block');//显示添加备注按钮
                        } else {
                            gritterAlert("{{ 'Alert'|trans }}", response.message, 'error');
                        }
                    }
                });
            });

            //复制IVR
            $('#copy_ivr').on('click', function () {
                if (!ivr_id) {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Copy Ivr not exist'|trans }}", 'error');
                    return false;
                }

                var ivr_name = $('#ivr_name_copy').val();
                if (!ivr_name) {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Input ivr name'|trans }}", 'error');
                    return false;
                }

                $.ajax({
                    url: "{{ path('icsoc_ivr_copy') }}",
                    dataType: 'json',
                    data: {ivr_name:ivr_name, ivr_id: ivr_id},
                    type: 'post',
                    success: function(response) {
                        if (response.code == 200) {
                            bootbox.confirm({
                                message: "{{ 'Copy Ivr success confirm'|trans }}",
                                buttons: {
                                    confirm: {
                                        label: "{{ 'yes'|trans }}",
                                        className: "btn-primary btn-sm"
                                    },
                                    cancel: {
                                        label: "{{ 'no'|trans }}",
                                        className: "btn-sm"
                                    }
                                },
                                callback: function(result) {
                                    if(result) {
                                        window.location.href = "{{ path('icsoc_ivr_edit') }}?id="+response.ivr_id;
                                    }
                                }
                            });
                        } else {
                            gritterAlert("{{ 'Alert'|trans }}", response.message, 'error');
                        }
                    }
                });
            });

            //添加备注
            $('#remark').on('click', function (){
                $( "#dialog-confirm" ).removeClass('hide').dialog({
                    resizable: false,
                    modal: false,
                    title_html: true,
                    height:170,
                    title: "{{ 'Add Remark'|trans }}"
                });
            });

            //保存备注
            $('#remark-btns').on('click', function (){
                var remark = $.trim($('#remark_val').val());
                if (!remark) {
                    $("#remark-confirm").removeClass('hide');
                    $("#remark_val").focus();
                    return false;
                }

                $.ajax({
                    url: "{{ path('icsoc_ivr_remark_add') }}",
                    dataType: 'json',
                    data: {remark:remark, ivr_id: ivr_id},
                    type: 'post',
                    success: function(response) {
                        if (response.code == 200) {
                            $('#remark_val').val('');
                            $("#remark-confirm").addClass('hide');
                            $("#dialog-confirm").dialog("close");
                        } else {
                            gritterAlert("{{ 'Alert'|trans }}", response.message, 'error');
                        }
                    }
                });
            });

            //返回
            $('#back').on('click', function () {
                location.href = '{{ path("icsoc_ivr_list") }}';
            })

            var setting = {
                view: {
                    showLine: true,
                    showIcon: true,
                    fontCss:getFont,
                    expandSpeed: "fast"
                },
                edit: {
                    enable: true,
                    showRemoveBtn: true,
                    showRenameBtn: false,
                    drag: {
                        isCopy: false,
                        isMove: false
                    },
                    removeTitle: "{{ 'Delete Node'|trans }}"
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                callback:{
                    onClick:onClickNode,
                    beforeRemove:function(treeId, treeNode){
                        delMsg = '';
                        delTid = treeNode.tId;
                        var ifDel = recursiveIfDeleteNodes(treeNode);
                        if (ifDel) {
                            gritterAlert("{{ 'Alert'|trans }}", ifDel, 'error');
                            return false;
                        }

                        if (treeNode.isDel == false) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'This Node Can Not Be Deleted'|trans }}", 'error');
                            return false;
                        }
                        if(treeNode.type == 1) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Root Node Can Not Be Deleted'|trans }}", 'error');
                            return false;
                        } else if (treeNode.condition == 'queue_fail') {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'This Node Can Not Be Deleted'|trans }}", 'error');
                            return false;
                        } else {
                            return confirm("{{ 'Confirm to delete this node?'|trans }}");
                        }
                    },
                    onRemove: function(event, treeId, treeNode) {
                        recursiveDeleteNodes(treeNode);
                        //更新父节点的状态
                        var parentId = treeNode.parentTId;
                        var treeObj = $.fn.zTree.getZTreeObj("tree");
                        var parentNode = treeObj.getNodeByTId(parentId);
                        parentNode.jump = '';
                        parentNode.nodeClass = $red;
                        parentNode.nodeStatus = false;
                        treeObj.updateNode(parentNode);
                    }
                }
            };

            if (ivr_id > 0) {
                var zNodes = '{{ ivr_content|default('')|raw }}';
                zNodes = JSON.parse(zNodes);
                oldJumpNode = zNodes.jump;
                recursiveAddNodes(zNodes);
                zNodes = recursiveJumpNodes(zNodes);

                $('#copy_ivr_div').css('display', 'inline-block');//显示复制IVR功能
                $('#remark_div').css('display', 'inline-block');//显示添加备注按钮
            } else {
                var zNodes = {"name": "{{ 'Default IVR'|trans }}", type: 1, "open": true, "isParent": true, "children": [],nodeClass:$red,nodeStatus:false,icon:"{{ asset('bundles/icsocivr/images/gongzuoshijian.png') }}"};
            }
            $.fn.zTree.init($("#tree"), setting, zNodes);
            //加载时默认选中根节点
            nodeRootAction(zNodes);
            selectedNode = $.fn.zTree.getZTreeObj("tree").getNodeByTId('tree_1');
        });

        //设置节点样式
        function getFont(treeId, node) {
            return node.nodeClass ? node.nodeClass : {};
        }
        //点击事件
        function onClickNode(event, treeId, treeNode) {
            selectedNode = treeNode;
            if (treeNode.parentTId) {
                variableNode = treeNode.parentTId.replace('tree_','');
            }
            //获取该节点的父节点用于获取变量
            allParentNode = [];
            checkAllParents(treeNode);
            oldJumpNode = treeNode.jump;
            sound_list = {'sound':0,'navigation_sound': 0,'error_key_sound':0,'none_key_sound':0,'before_conn_sound':0,'agent_side_sound':0};

            /* 点击节点时，设置节点的信息 */
            switch(parseInt(treeNode.type)) {
                case 1://根节点
                    nodeRootAction(treeNode);
                    break;
                case 2://播放语音
                    nodeSoundAction(treeNode);
                    break;
                case 3://按键导航
                    nodeNavigationAction(treeNode);
                    break;
                case 30://按键导航下的具体按键
                    nodeNavigationKeyAction(treeNode);
                    break;
                case 5://转技能组
                    nodeQueueAction(treeNode);
                    break;
                case 50://转技能组子节点
                    nodeQueueChildrenAction(treeNode);
                    break;
                case 6://留言
                    nodeMessageAction(treeNode);
                    break;
                case 7://挂机
                    nodeHangupAction(treeNode);
                    break;
                case 8://收号
                    nodeKeysAction(treeNode);
                    break;
                case 80://收号子节点
                    nodeKeysChildrenAction(treeNode);
                    break;
                case 9://接口交互
                    nodeHttpAction(treeNode);
                    break;
                case 90://接口交互子节点
                    nodeHttpChildrenAction(treeNode);
                    break;
                case 10://来电记忆
                    nodeMemoryAction(treeNode);
                    break;
                case 100://来电记忆子节点
                    nodeMemoryChildrenAction(treeNode);
                    break;
                case 11://转电话
                    nodePhoneAction(treeNode);
                    break;
                case 12://转坐席
                    nodeAgentAction(treeNode);
                    break;
                case 13://判断
                    var  nodeJudge = '';
                    nodeJudgeAction(treeNode);
                    break;
                case 130://判断子节点
                    nodeJudgeChildrenAction(treeNode);
                    break;
                case 14://转IVR
                    nodeIvrAction(treeNode);
                    break;					
                default:
                    $('#nodeAttr').html('');
                    break;
            }
        }

        //根节点操作
        function nodeRootAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_root_attr") }}',
                callback: function(response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    setIvrCountName(treeNode);
                    $('#form_jump_nodes').val(treeNode.jump);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-save-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');

                //验证节点数据
                if (!$jump.val()) {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.name = selectedNode.tId.replace('tree_', '') + '-' + selectedNode.name;
                selectedNode.jump = $jump.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //播放语音节点操作
        function nodeSoundAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_sound_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $form_jump_nodes = $('#form_jump_nodes');
                    updateJumpNodes($form_jump_nodes);
                    $form_jump_nodes.val(treeNode.jump);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    handleSoundView(treeNode, 'sound', 'sound');
                    $('#form_bkeystop').val(treeNode.bkeystop || 0);
                    $('#form_play_times').val(treeNode.play_times || 1);
                    setIvrCountName(treeNode);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');
                var $play_times = $('#form_play_times');
                var $bkeystop = $('#form_bkeystop');

                //验证语音
                if (checkt_sound(sound_list.sound,'sound') == false){
                    selectedNode.nodeStatus = false;
                    return false;
                }
                //验证跳转节点
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                save_sound(sound_list.sound,'sound');
                selectedNode.jump = $jump.val();
                selectedNode.bkeystop = $bkeystop.val();
                selectedNode.play_times = $play_times.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //按键导航节点操作
        function nodeNavigationAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_navigation_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示

                    $('#form_name').val(treeNode.name);
                    handleSoundView(treeNode, 'navigation_sound', 'navigation_sound');
                    $('#form_timeout').val(treeNode.timeout || 10);
                    $('#form_play_times').val(treeNode.play_times || 1);
                    $('#form_navigation_keys').val(treeNode.navigation_keys || []);
                    handleSoundView(treeNode, 'error_key_sound', 'error_key_sound');
                    handleSoundView(treeNode, 'none_key_sound', 'none_key_sound');
                    $('#form_if_enable_multi_keys').val(treeNode.if_enable_multi_key || 0);
                    $('#form_multi_keys_start').val(treeNode.multi_keys_start || '');
                    $('#form_max_keys_length').val(treeNode.multi_keys_length || 4);
                    setIvrCountName(treeNode);
                    //设置多按键div显示
                    fn_if_enable_multi_keys();
                    handleKeys();
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $play_times = $('#form_play_times');
                var $timeout = $('#form_timeout');
                var $navigation_keys = $('#form_navigation_keys');
                var $if_enable_multi_key = $('#form_if_enable_multi_keys');
                var $multi_keys_start = $('#form_multi_keys_start');
                var $multi_keys_length = $('#form_max_keys_length');

                //验证导航语音
                if (checkt_sound(sound_list.navigation_sound,'navigation_sound') == false) {
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //验证
                if (!$navigation_keys.val()) {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Select Navigation Keys'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }
                //启用多按键
                if ($if_enable_multi_key.val() != 0) {
                    if (!$multi_keys_start.val()) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Select Multi Start Keys'|trans }}", 'error');
                        selectedNode.nodeStatus = false;
                        return false;
                    }

                    if (!$multi_keys_length.val() || $multi_keys_length.val() <= 1 || $multi_keys_length.val() > 32) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'multi keys alert'|trans }}", 'error');
                        selectedNode.nodeStatus = false;
                        return false;
                    }
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.play_times = $play_times.val();
                selectedNode.timeout = $timeout.val();
                selectedNode.navigation_keys = $navigation_keys.val();
                selectedNode.if_enable_multi_key = $if_enable_multi_key.val();
                selectedNode.multi_keys_start = $multi_keys_start.val();
                selectedNode.multi_keys_length = $multi_keys_length.val();
                save_sound(sound_list.navigation_sound,'navigation_sound');
                save_sound(sound_list.error_key_sound,'error_key_sound');
                save_sound(sound_list.none_key_sound,'none_key_sound');
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);
                if ($if_enable_multi_key.val() == 1) {
                    selectedNode.navigation_keys[selectedNode.navigation_keys.length] = "multiKeys";
                }

                appendNavigationKeys(selectedNode.navigation_keys, treeObj);
                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
            });
        }

        //按键导航节点具体按键操作
        function nodeNavigationKeyAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_navigation_key_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $jump = $('#form_jump_nodes');
                    updateJumpNodes($jump);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    if (treeNode.condition == 'multiKeys') {//启用多按键
                        $('#form_multi_keys_type').val(treeNode.multi_keys_type || 0);
                        $('#form_variable_name').val(treeNode.variable_name || '');
                        var is_tran_front = typeof(treeNode.is_tran_front) == 'undefined' ? 0 : treeNode.is_tran_front;
                        $("input[type=radio][name=is_tran_front][value="+is_tran_front+"]").attr("checked",'checked')
                    } else {
                        $('#form_multi_keys_type').val('');
                        $("#form_multi_keys_type_div").addClass('hidden');
                        $("#form_variable_name_div").addClass('hidden');
                        $("#is_tran_front_div").addClass('hidden');
                    }
                    setIvrCountName(treeNode);
                    $jump.val(treeNode.jump);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');
                var $multi_keys_type = $('#form_multi_keys_type');
                var $variable_name = $('#form_variable_name');
                var variableValue = $.trim($variable_name.val());
                var $is_tran_front = $('input[name="is_tran_front"]:checked');

                if (treeNode.condition == 'multiKeys') {
                    //验证变量是否输入
                    if (!variableValue) {
                        $variable_name.focus();
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Input variable name'|trans }}", 'error');
                        selectedNode.nodeStatus = false;
                        return false;
                    }

                    //验证变量名称是否合法
                    if (!checkVariable(variableValue)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'variable illegal tips'|trans }}", 'error');
                        selectedNode.nodeStatus = false;
                        return false;
                    }

                    //验证变量是否存在
                    if (variableValue != treeNode.variable_name && checkVariableIfExist(variableValue) == true) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'variable name already exists'|trans }}", 'error');
                        selectedNode.nodeStatus = false;
                        return false;
                    }

                    //设置变量
                    variableName.custom[treeNode.tId]= variableValue;

                    //更新变量
                    if ( treeNode.variable_name && variableValue != treeNode.variable_name) {
                        vars = false;
                        updateChildNodeVar(treeNode, treeNode.variable_name, variableValue);
                    }
                }

                //验证跳转节点
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.multi_keys_type = $multi_keys_type.val();
                selectedNode.variable_name = variableValue;
                selectedNode.jump = $jump.val();
                selectedNode.is_tran_front = $is_tran_front.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //转技能组节点操作
        function nodeQueueAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_queue_attr") }}',
                callback: function (response) {
                    var res = false;
                    function getParentPath(treeNode){
                        var node = treeNode.getParentNode();
                        var nodes = node.getParentNode();
                        if (node.type && node.type == 100 && node.condition == 'return_success' && nodes.memory_type == 1) {
                            res = true;
                            return res
                        } else {
                            if (res != true) {
                                if (node.parentTId != null) {
                                    getParentPath(node);
                                }
                            }
                        }

                        return res;
                    }

                    var ifexistmemnode = getParentPath(treeNode)

                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    $('#form_transfer_type').val(treeNode.transfer_type || 'fixed');
                    if (res != true ) $("#form_transfer_type option[value='memory']").remove();
                    $('#form_variable_name').val(treeNode.variable_name || '');
                    $('#form_queue').val(treeNode.queue);
                    $('#form_if_enable_queue_timeout_continue').val(treeNode.if_enable_queue_timeout_continue || 0);
                    $('#form_max_queue_times').val(treeNode.max_queue_times || 1);
                    $('#form_if_handle_none_agent').val(treeNode.if_handle_none_agent || 0);
                    $('#form_if_handle_queue_times_exceed').val(treeNode.if_handle_queue_times_exceed || 0);
                    $('#form_if_handle_queue_full').val(treeNode.if_handle_queue_full || 0);
                    $('#form_if_handle_queue_timeout').val(treeNode.if_handle_queue_timeout || 0);
                    handleSoundView(treeNode, 'sound', 'sound');
                    handleSoundView(treeNode, 'before_conn_sound', 'before_conn_sound');
                    handleSoundView(treeNode, 'agent_side_sound', 'agent_side_sound');
                    form_transfer_type();
                    if_enable_queue_timeout_continue();
                    $('#form_if_open_vip').val(treeNode.if_open_vip || 0);
                    $('#form_api_url').val(treeNode.api_url || '');
                    $('#form_api_method').val(treeNode.api_method || 'get');
                    $('#form_api_timeout').val(treeNode.api_timeout || 5);
                    if_open_vip();
                    if (typeof(treeNode.api_params) == 'object' && isNullObj(treeNode.api_params) == false) {
                        var i = 0;
                        $.each(treeNode.api_params, function (index,data) {
                            var type = i == 0 ? 'plus' : 'minus';
                            setApiParames(type, data);
                            i++;
                        });
                    } else {
                        setApiParames('plus');
                    }
                    setIvrCountName(treeNode);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $transfer_type = $('#form_transfer_type');
                var $variable_name = $('#form_variable_name');
                var $queue = $('#form_queue');
                var $if_enable_queue_timeout_continue = $('#form_if_enable_queue_timeout_continue');
                var $max_queue_times = $('#form_max_queue_times');
                var $if_handle_none_agent = $('#form_if_handle_none_agent');
                var $if_handle_queue_times_exceed = $('#form_if_handle_queue_times_exceed');
                var $if_handle_queue_full = $('#form_if_handle_queue_full');
                var $if_handle_queue_timeout = $('#form_if_handle_queue_timeout');
                var $form_if_open_vip = $('#form_if_open_vip');
                var $form_api_url = $('#form_api_url');
                var $form_api_method = $('#form_api_method');
                var $form_api_timeout = $('#form_api_timeout');
                var $form = $("#form");

                /** 验证技能组选择 */
                switch ($transfer_type.val()) {
                    case 'fixed'://固定技能组
                        if (!$queue.val()) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Select Queues'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    case 'variable':
                        if (!$variable_name.val()) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Variable'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    case 'memory':
                        break;
                    default :
                        selectedNode.nodeStatus = false;
                        return false;
                        break;
                }

                /** 验证开启VIP功能相关参数是否设置 */
                if ($form_if_open_vip.val() == 1) {
                    var validate = true;

                    if( !$form.validate().element($form_api_url) ) {
                        validate = false;
                    }

                    if (validate === false) {
                        selectedNode.nodeStatus = false;
                        return false;
                    } else if ($.trim($form_api_url.val()) == '') {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Api Url cannot be empty'|trans  }}", 'error');
                        selectedNode.nodeStatus = false;
                        return false;
                    }
                }

                var params = {};
                $("#form_api_params").children().not('.hidden').each(function() {
                    var $api_params_type = $.trim($(this).find("[name='form[api_params_type]']").val());
                    var $api_params_name = $.trim($(this).find("[name='form[api_params_name]']").val());
                    if ($api_params_type == 1) {
                        var $api_params_value = $.trim($(this).find("[datatype='variable']").val());
                    } else {
                        var $api_params_value = $.trim($(this).find("[datatype='fixed']").val());
                    }

                    if ($api_params_name != '') {
                        var param = {"params_type":$api_params_type,"params_name":$api_params_name,"params_value":$api_params_value};
                        params[$api_params_name] = param;
                    }

                });

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.transfer_type = $transfer_type.val();
                selectedNode.variable_name = $variable_name.val();
                selectedNode.queue = $queue.val();
                selectedNode.if_enable_queue_timeout_continue = $if_enable_queue_timeout_continue.val();
                selectedNode.max_queue_times = $max_queue_times.val();
                selectedNode.if_handle_none_agent = $if_handle_none_agent.val();
                selectedNode.if_handle_queue_times_exceed = $if_handle_queue_times_exceed.val();
                selectedNode.if_handle_queue_full = $if_handle_queue_full.val();
                selectedNode.if_handle_queue_timeout = $if_handle_queue_timeout.val()
                save_sound(sound_list.sound,'sound');
                save_sound(sound_list.before_conn_sound,'before_conn_sound');
                save_sound(sound_list.agent_side_sound,'agent_side_sound');

                selectedNode.if_open_vip = $form_if_open_vip.val();
                selectedNode.api_url = $.trim($form_api_url.val());
                selectedNode.api_method = $form_api_method.val();
                selectedNode.api_timeout = $form_api_timeout.val();
                selectedNode.api_params = params;
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);
                appendQueueNodes(selectedNode, treeObj);

                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
            });
        }
        //转技能组节点子节点操作
        function nodeQueueChildrenAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_queue_children_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $jump = $('#form_jump_nodes');
                    updateJumpNodes($jump);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    handleSoundView(treeNode, 'sound', 'sound');
                    setIvrCountName(treeNode);
                    $jump.val(treeNode.jump);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');

                //验证
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                save_sound(sound_list.sound,'sound');
                selectedNode.jump = $jump.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //留言节点操作
        function nodeMessageAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_message_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    setIvrCountName(treeNode);
                    handleSoundView(treeNode, 'sound', 'sound');
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                save_sound(sound_list.sound,'sound');
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);
                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
            });
        }

        //挂机节点操作
        function nodeHangupAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_hangup_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                }
            });
        }

        //收号节点操作
        function nodeKeysAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_keys_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    $('#form_play_times').val(treeNode.play_times || 1);
                    $('#form_max_keys_length').val(treeNode.max_keys_length || 4);
                    $('#form_timeout').val(treeNode.timeout || 10);
                    $('#form_variable_name').val(treeNode.variable_name || '');
                    var is_tran_front = typeof(treeNode.is_tran_front) == 'undefined' ? 0 : treeNode.is_tran_front;
                    $("input[type=radio][name=is_tran_front][value="+is_tran_front+"]").attr("checked",'checked')
                    setIvrCountName(treeNode);
                    handleSoundView(treeNode, 'sound', 'sound');
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $play_times = $('#form_play_times');
                var $max_keys_length = $('#form_max_keys_length');
                var $timeout = $('#form_timeout');
                var $variable_name = $('#form_variable_name');
                var $is_tran_front = $('input[name="is_tran_front"]:checked');

                //验证语音
                if (checkt_sound(sound_list.sound,'sound') == false){
                    selectedNode.nodeStatus = false;
                    return false;
                }
                //验证最大收键长度
                if (!$max_keys_length.val() || $max_keys_length.val() <= 0 ||  $max_keys_length.val() >32) {
                    $max_keys_length.focus();
                    selectedNode.nodeStatus = false;
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'keys lenght alert'|trans }}", 'error');
                    return false;
                }

                var variableValue = $.trim($variable_name.val());

                //验证变量是否输入
                if (!variableValue) {
                    $variable_name.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Input variable name'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //验证变量名称是否合法
                if (!checkVariable(variableValue)) {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'variable illegal tips'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //验证变量是否存在
                if (variableValue != treeNode.variable_name && checkVariableIfExist(variableValue) == true) {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'variable name already exists'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //在全局变量保存设置的变量
                variableName.custom[treeNode.tId]= variableValue;

                //更新子节点中用的的变量
                if (treeNode.variable_name && variableValue != treeNode.variable_name) {
                    vars = false;
                    updateChildNodeVar(treeNode, treeNode.variable_name, variableValue);
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.play_times = $play_times.val();
                selectedNode.max_keys_length = $max_keys_length.val();
                selectedNode.timeout = $timeout.val();
                selectedNode.variable_name = variableValue;
                selectedNode.is_tran_front = $is_tran_front.val();

                save_sound(sound_list.sound,'sound');
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);
                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
            });
        }

        //收号节点子节点操作
        function nodeKeysChildrenAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_keys_children_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $jump = $('#form_jump_nodes');
                    updateJumpNodes($jump);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    setIvrCountName(treeNode);
                    $jump.val(treeNode.jump);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');

                //验证跳转节点
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.jump = $jump.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //接口交互节点操作
        function nodeHttpAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_http_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    $('#form_api_url').val(treeNode.api_url || '');
                    $('#form_api_params').val(treeNode.api_params || '');
                    $('#form_request_method').val(treeNode.request_method || 'get');
                    $('#form_timeout').val(treeNode.timeout || 5);
                    $('#form_variable_name').val(treeNode.variable_name || '');
                    $("#form_api_params").empty();
                    var is_tran_front = typeof(treeNode.is_tran_front) == 'undefined' ? 0 : treeNode.is_tran_front;
                    $("input[type=radio][name=is_tran_front][value="+is_tran_front+"]").attr("checked",'checked')
                    setIvrCountName(treeNode);
                    setApiParames(treeNode.api_params_original || '');
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $form = $("#form");
                var $api_url = $('#form_api_url');
                var $api_params = $('#form_api_params');
                var $request_method = $('#form_request_method');
                var $timeout = $('#form_timeout');
                var $variable_name = $('#form_variable_name');
                var $is_tran_front = $('input[name="is_tran_front"]:checked');

                /**
                 * 验证表单
                 */

                var validate = true;

                if( !$form.validate().element($api_url) ) {
                    validate = false;
                }

                if( !$form.validate().element($variable_name) ) {
                    validate = false;
                }

                if (validate === false) {
                    selectedNode.nodeStatus = false;
                    return false;
                }

               var  variableVal = $variable_name.val().replace(/，/gm,',');

                //更新变量
                if (treeNode.variable_name && variableVal != treeNode.variable_name) {
                    vars = false;
                    vars = updateChildNodeVar(treeNode, treeNode.variable_name, variableVal)
                    if (vars) {
                        vars = vars.split(',');
                        gritterAlert("{{ 'Alert'|trans }}", vars[1]+"{{ 'Cannot delete'|trans }}"+ "["+vars[0]+"]" +"{{ 'Cannot delete1'|trans }}", 'error');
                        selectedNode.nodeStatus = false;
                        $variable_name.val(treeNode.variable_name);
                        return false;
                    }
                }

                //设置变量
                variableName.custom[treeNode.tId]= variableVal;

                var paramsValue = [];
                var paramsOriginal = [];
                for(var i=0;i<paramsIndex;i++) {
                    if ($("#form_api_params_"+i).length > 0) {
                        var $params_type = $('#form_params_type_'+i).val();
                        var $params_name = $('#form_api_params_name_'+i).val();

                        paramsOriginal[i] = {};
                        paramsOriginal[i].params_type = $params_type;
                        paramsOriginal[i].params_name = $params_name;

                        switch ($params_type) {
                            case '0':
                                var $params_value = $('#form_api_params_value_'+i).val();
                                paramsOriginal[i].params_value = $params_value;
                                break;
                            case '1':
                                var $params_value = "${"+$('#form_api_params_value_variable_'+i).val()+"}";
                                paramsOriginal[i].params_value = $('#form_api_params_value_variable_'+i).val();
                                break;
                        }

                        if ($params_name) {
                            paramsValue.push($params_name+"="+$params_value);
                        }

                    }
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.api_url = $api_url.val();
                selectedNode.api_params_original = paramsOriginal;
                selectedNode.api_params = paramsValue.join('&');
                selectedNode.request_method = $request_method.val();
                selectedNode.timeout = $timeout.val();
                selectedNode.variable_name = variableVal;
                selectedNode.is_tran_front = $is_tran_front.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);
                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
            });
        }
        //接口交互节点子节点操作
        function nodeHttpChildrenAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_http_children_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $jump = $('#form_jump_nodes');
                    updateJumpNodes($jump);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    setIvrCountName(treeNode);
                    $jump.val(treeNode.jump);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');

                //验证
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.jump = $jump.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //来电记忆节点操作
        function nodeMemoryAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_memory_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    $('#form_memory_type').val(treeNode.memory_type || 1);
                    $('#form_cdr_type').val(treeNode.cdr_type || 'all');
                    $('#form_queue').val(treeNode.queue);
                    $('#form_last_call_time').val(treeNode.last_call_time || 1);
                    $('#form_time_unit').val(treeNode.time_unit || 'hour');
                    $('#form_custom_api_url').val(treeNode.custom_api_url || '');
                    form_memory_type();
                    setApiParames(treeNode.custom_api_params || '');
                    setIvrCountName(treeNode);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
        }
        });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $memory_type = $('#form_memory_type');
                var $cdr_type = $('#form_cdr_type');
                var $queue = $('#form_queue');
                var $last_call_time = $('#form_last_call_time');
                var $time_unit = $('#form_time_unit');
                var $custom_api_url = $('#form_custom_api_url');

                var custom_api_params = [];

                //验证
                switch ($memory_type.val()) {
                    case '1'://通话记录
                        if (!$cdr_type.val()) {
                            $cdr_type.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select cdr type'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        if (!$last_call_time.val()) {
                            $last_call_time.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select last call time'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        if (!$time_unit.val()) {
                            $time_unit.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select time unit'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    case '3'://自定义接口
                        if (!$custom_api_url.val()) {
                            $custom_api_url.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please input custom api url'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }

                        //处理自定义接口参数
                        for(var i=0;i<paramsIndex;i++) {
                            if ($("#form_api_params_"+i).length > 0) {
                                var $params_type = $('#form_params_type_'+i).val();
                                var $params_name =  $.trim($('#form_api_params_name_'+i).val());
                                var $params_value = $.trim($('#form_api_params_value_variable_'+i).val());
                                custom_api_params[i] = {};
                                custom_api_params[i].params_type = $params_type;
                                custom_api_params[i].params_name = $params_name;
                                switch ($params_type) {
                                    case '0':
                                        var $params_value = $.trim($('#form_api_params_value_'+i).val());
                                        break;
                                    case '1':
                                        var $params_value = $.trim($('#form_api_params_value_variable_'+i).val());
                                        break;
                                }

                                custom_api_params[i].params_value = $params_value;
                            }
                        }
                        break;
                    default:
                        break;
                }



                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.memory_type = $memory_type.val();
                selectedNode.cdr_type = $cdr_type.val();
                selectedNode.queue = $queue.val();
                selectedNode.last_call_time = $last_call_time.val();
                selectedNode.time_unit = $time_unit.val();
                selectedNode.custom_api_url = $custom_api_url.val();
                selectedNode.custom_api_params = custom_api_params;
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);
                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
            });
        }

        //来电记忆子节点操作
        function nodeMemoryChildrenAction(treeNode)
        {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_http_children_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $jump = $('#form_jump_nodes');
                    updateJumpNodes($jump);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    setIvrCountName(treeNode);
                    $jump.val(treeNode.jump);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');

                //验证
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.jump = $jump.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //转电话节点操作
        function nodePhoneAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_phone_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $form_jump_nodes = $('#form_jump_nodes');
                    updateJumpNodes($form_jump_nodes);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    $('#form_phone_line').val(treeNode.phone_line || 0);
                    $('#form_phone_type').val(treeNode.phone_type || 'fixed');
                    $('#form_phone_num').val(treeNode.phone_num || '');
                    $('#form_variable_name').val(treeNode.variable_name || '');
                    $('#form_caller_variable_name').val(treeNode.caller_variable_name || '');
                    $('#form_caller_type').val(treeNode.caller_type || 'select');
                    if (treeNode.caller) {
                        $('#form_caller').val(treeNode.caller);
                    } else {
                        $('#form_caller').get(0).selectedIndex=0;
                    }
                    $form_jump_nodes.val(treeNode.jump);
                    form_phone_line();
                    form_phone_type();
                    form_caller_type();
                    setIvrCountName(treeNode);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');
                var $phone_line = $('#form_phone_line');
                var $phone_type = $('#form_phone_type');
                var $phone_num = $('#form_phone_num');
                var $variable_name = $('#form_variable_name');
                var $caller = $('#form_caller');
                var $calle_type = $('#form_caller_type');
                var $caller_variable_name = $('#form_caller_variable_name');

                //验证转接电话
                switch ($phone_type.val()) {
                    case 'fixed'://固定电话
                        if (!checkIfnumber($.trim($phone_num.val()))) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'phone verify tips'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    case 'variable'://变量
                        if (!$variable_name.val()) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Variable'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    default :
                        selectedNode.nodeStatus = false;
                        return false;
                        break;
                }

                //验证显示的主叫号码
                switch ($calle_type.val()) {
                    case 'select'://选择主叫
                        if (!$caller.val()) {
                            $caller.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select caller'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    case 'caller_variable'://变量
                        if (!$caller_variable_name.val()) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Caller Variable'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    default :
                        selectedNode.nodeStatus = false;
                        return false;
                        break;
                }

                //验证跳转节点
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.jump = $jump.val();
                selectedNode.phone_line = $phone_line.val();
                selectedNode.phone_type = $phone_type.val();
                selectedNode.phone_num = $.trim($phone_num.val());
                selectedNode.variable_name = $variable_name.val();
                selectedNode.caller = $caller.val();
                selectedNode.caller_type = $calle_type.val();
                selectedNode.caller_variable_name = $caller_variable_name.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //转坐席节点操作
        function nodeAgentAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_agent_attr") }}',
                callback: function (response) {
                    //判断父节点中是否存在来电记忆节点如果不存在去掉来电记忆类型
                    var res = false;
                    function getParentPath(treeNode){
                        var node = treeNode.getParentNode();
                        if (node.type && node.type == 100 && node.condition == 'return_success' ) {
                            res = true;
                            return res
                        } else {
                            if (res != true) {
                                if (node.parentTId != null) {
                                    getParentPath(node);
                                }
                            }
                        }

                        return res;
                    }

                    var ifexistmemnode = getParentPath(treeNode)
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $form_jump_nodes = $('#form_jump_nodes');
                    updateJumpNodes($form_jump_nodes);
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    $form_jump_nodes.val(treeNode.jump);
                    $('#form_transfer_type').val(treeNode.transfer_type || 'fixed');
                    if (res != true ) $("#form_transfer_type option[value='memory']").remove();
                    $('#form_agent').val(treeNode.agent || '');
                    $('#form_variable_name').val(treeNode.variable_name || '');
                    //$('#form_if_enable_when_agent_is_not_login_transfer_to_mobile').val(treeNode.if_enable_when_agent_is_not_login_transfer_to_mobile || 0);
                    $('#form_transfer_mode').val(treeNode.transfer_mode || 1);
                    form_transfer_type();
                    setIvrCountName(treeNode);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');
                var $transfer_type = $('#form_transfer_type');
                var $agent = $('#form_agent');
                var $variable_name = $('#form_variable_name');
                //var $if_enable_when_agent_is_not_login_transfer_to_mobile = $('#form_if_enable_when_agent_is_not_login_transfer_to_mobile');
                var $transfer_mode = $('#form_transfer_mode');

                //验证
                switch ($transfer_type.val()) {
                    case 'fixed'://固定坐席
                        if (!$agent.val()) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Select Agents'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    case 'variable':
                        if (!$variable_name.val()) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Variable'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        break;
                    case 'memory':
                        break;
                    default :
                        selectedNode.nodeStatus = false;
                        return false;
                        break;
                }
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.transfer_type = $transfer_type.val();
                selectedNode.agent = $agent.val();
                selectedNode.variable_name = $variable_name.val();
                selectedNode.jump = $jump.val();
                //selectedNode.if_enable_when_agent_is_not_login_transfer_to_mobile = $if_enable_when_agent_is_not_login_transfer_to_mobile.val();
                selectedNode.transfer_mode = $transfer_mode.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }

        //判断节点操作
        function nodeJudgeAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_judge_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
                    setIvrCountName(treeNode);
                    handleConditionsView(treeNode);
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var children11 = treeObj.getNodeByParam('type', 13, selectedNode.getParentNode()).children;
                var conditions = [];
                for(var i=0;i<conditionsIndex;i++) {
                    if ($("#form_conditions_"+i).length > 0) {
                        var $conditionsName = $('#form_conditions_name_'+i);
                        if (!$.trim($conditionsName.val())) {
                            $conditionsName.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Set Conditions'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }

                        //判断是否存在相同条件名称
                        if ($.inArray($.trim($conditionsName.val()), conditions) != -1) {
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'The condition with the same name already exists'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        conditions.push($.trim($conditionsName.val()));
                    }
                }

                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                selectedNode.conditions = [];
                //设置条件
                var j = 0;
                for(var i=0;i<conditionsIndex;i++) {
                    if ($("#form_conditions_"+i).length > 0) {
                        var $conditionsName = $('#form_conditions_name_'+i);
                        if (!$.trim($conditionsName.val())) {
                            $conditionsName.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Set Conditions'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        selectedNode.conditions[j] = $.trim($conditionsName.val());
                        j++;
                    }
                }

                appendJudgeKeys(selectedNode.conditions,treeObj);
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);

            });
        }

        //判断节点子节点操作
        function nodeJudgeChildrenAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_judge_children_attr") }}',
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //更新跳转节点数据
                    var $jump = $('#form_jump_nodes');
                    updateJumpNodes($jump);
                    //设置节点显示
                    if (treeNode.condition == 'judge_fail') {
                        $('#form_conditions').addClass('hidden');
                        $('#node_type').val('fail');
                    }
                    $('#form_name').val(treeNode.name);
                    handleConditionsView(treeNode);
                    setIvrCountName(treeNode);
                    $jump.val(treeNode.jump);
                    $('.chosen-select').chosen({width: '350px', allow_single_deselect:true});
                }
            });
            //保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var $jump = $('#form_jump_nodes');
                var node_type = $('#node_type').val();

                if (node_type != 'fail') {
                //验证判断条件
                for(var i=0;i<=form_and_index;i++) {
                    if ($("#form_and_"+i).length > 0) {
                        var $conditionsVariable = $('#form_and_variable_'+i);
                        var $conditionsRelation = $('#form_and_relation_'+i);
                        var $conditionsConditions = $('#form_and_conditions_'+i);
                        if (!$conditionsVariable.val()) {
                            $conditionsVariable.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Variable'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        if (!$conditionsRelation.val()) {
                            $conditionsRelation.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Relation'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        if (!$.trim($conditionsConditions.val())) {
                            $conditionsConditions.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Set Conditions'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                    }
                }

                for(var i=0;i<=form_or_index;i++) {
                    if ($("#form_or_"+i).length > 0) {
                        var $conditionsVariable = $('#form_or_variable_'+i);
                        var $conditionsRelation = $('#form_or_relation_'+i);
                        var $conditionsConditions = $('#form_or_conditions_'+i);
                        if (!$conditionsVariable.val()) {
                            $conditionsVariable.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Variable'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        if (!$conditionsRelation.val()) {
                            $conditionsRelation.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Selected Relation'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                        if (!$.trim($conditionsConditions.val())) {
                            $conditionsConditions.focus();
                            gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Set Conditions'|trans }}", 'error');
                            selectedNode.nodeStatus = false;
                            return false;
                        }
                    }
                }

                }
                //验证跳转节点
                if (!$jump.val()) {
                    $jump.focus();
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please select jump node'|trans }}", 'error');
                    selectedNode.nodeStatus = false;
                    return false;
                }

                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                if (node_type != 'fail') {


                selectedNode.and = [];
                var j = 0;
                for(var i=0;i<form_and_index;i++) {
                    if ($("#form_and_"+i).length > 0) {
                        var $conditionsVariable = $('#form_and_variable_'+i);
                        var $conditionsRelation = $('#form_and_relation_'+i);
                        var $conditionsConditions = $('#form_and_conditions_'+i);
                        selectedNode.and[j] = {};
                        selectedNode.and[j].variable_name = $conditionsVariable.val();
                        selectedNode.and[j].relation = $conditionsRelation.val();
                        selectedNode.and[j].conditions = $conditionsConditions.val();
                        j++;
                    }
                }

                selectedNode.or = [];
                var j = 0;
                for(var i=0;i<form_or_index;i++) {
                    if ($("#form_or_"+i).length > 0) {
                        var $conditionsVariable = $('#form_or_variable_'+i);
                        var $conditionsRelation = $('#form_or_relation_'+i);
                        var $conditionsConditions = $('#form_or_conditions_'+i);
                        selectedNode.or[j] = {};
                        selectedNode.or[j].variable_name = $conditionsVariable.val();
                        selectedNode.or[j].relation = $conditionsRelation.val();
                        selectedNode.or[j].conditions = $conditionsConditions.val();
                        j++;
                    }
                }
                }

                if (node_type != 'fail') {
                    if ( selectedNode.or.length<=0 && selectedNode.and.length<=0) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Set Conditions'|trans }}", 'error');
                        selectedNode.nodeStatus = false;
                        return false;
                    }
                }


                selectedNode.jump = $jump.val();
                updateSelectNodeIvrCountInfo();
                treeObj.updateNode(selectedNode);
                if (oldJumpNode != $jump.val()) {
                    //将节点添加到树
                    if (oldJumpNode != $jump.val() && appendJumpNodesToTree($jump.val(), treeObj)) {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                    } else {
                        gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr failure!'|trans }},{{ 'append jump nodes faile message'|trans }}", 'error');
                    }
                } else {
                    gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
                }
            });
        }
		
		//转IVR节点操作
        function nodeIvrAction(treeNode) {
            //异步加载属性表单
            loadNodeAttribute({
                url: '{{ path("icsoc_ivr_node_ivr_attr") }}',
				data: {"ivr_id": ivr_id},
                callback: function (response) {
                    $('#nodeAttr').html(response);
                    $('[data-rel=popover]').popover({container:'body'});
                    //设置节点显示
                    $('#form_name').val(treeNode.name);
					$('#form_ivr_list').val(treeNode.ivr_node_ivr_code || '');
					getIvrNode(treeNode.ivr_node_ivr_code);
					$('#form_ivr_node').val(treeNode.ivr_node_ivr_node || '');
					setIvrCountName(treeNode);
                }
            });
			//保存属性
            $('#btn-node-attr').on('click', function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
				var ivr
                //保存设置的值
                selectedNode.nodeClass = $green;
                selectedNode.nodeStatus = true;
                updateSelectNodeIvrCountInfo();
				var ivr_code = $('#form_ivr_list').val();
				var ivr_node = $('#form_ivr_node').val();
				if (ivr_code.length < 1 || ivr_node.length<1) {
					gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Select ivr or ivr node'|trans }}", 'error');
					selectedNode.nodeStatus = false;
					return false;
				}
				selectedNode.ivr_node_ivr_code = ivr_code;
				selectedNode.ivr_node_ivr_node = ivr_node;
                treeObj.updateNode(selectedNode);
                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Save node attr success!'|trans }}", 'success');
            });
        }

        //加载节点属性
        function loadNodeAttribute(obj) {
            $.ajax({
                url: obj.url,
                data: obj.data || {},
                dataType: 'html',
                cache: false,
                async: false,
                success: obj.callback
            });
        }
        //更新跳转节点
        function updateJumpNodes($form_jump_nodes) {
            $form_jump_nodes = $form_jump_nodes || $('#form_jump_nodes');
            var options = '<optgroup label="{{ 'Current Nodes'|trans }}">';
            $.each(allNodes, function(index, value) {
                if (value.nodeType != 7) {
                    options += '<option value="'+index+'">'+value.id+'</option>';
                }
            });
            options += '</optgroup>';
            //$(options).insertAfter($form_jump_nodes.children()[0]);
            $(options).appendTo($form_jump_nodes);
        }
        //添加当前节点的跳转节点
        function appendJumpNodesToTree(nodeType, treeObj) {
            //每个节点只能添加一个子几点
            if(typeof selectedNode.children == "undefined" || selectedNode.children.length == 0) {
                var nodeName = 'node_'+nodeType;
                var newNode = null;
                //添加新建节点
                if (defaultNewNodes[nodeName]) {
                    //设置节点样式，未保存的节点字体为红色
                    defaultNewNodes[nodeName].nodeClass = nodeType == 7 ? $green : $red;
                    defaultNewNodes[nodeName].nodeStatus = nodeType == 7 ? true : false;
                    if (defaultNewNodes[nodeName].children) {
                        $.each(defaultNewNodes[nodeName].children, function(index) {
                            defaultNewNodes[nodeName].children[index].nodeClass = $red;
                            defaultNewNodes[nodeName].children[index].nodeStatus = false;
                        });
                    }
                    treeObj.addNodes(selectedNode, defaultNewNodes[nodeName]);
                    newNode = selectedNode.children[0];
                    newNode.name = newNode.tId.replace('tree_', '') + '-' + newNode.name;
                    treeObj.updateNode(newNode);
                    //选中新添加的节点
                    treeObj.selectNode(newNode);
                    onClickNode(null, null, newNode);
                    allNodes[newNode.tId] = [];
                    allNodes[newNode.tId]['id'] = newNode.name;
                    allNodes[newNode.tId]['nodeType'] = nodeType;
                    allSelectNodes[newNode.tId] = selectedNode;
                } else {
                    //添加已存在的节点
                    newNode = {name:allNodes[nodeType]['id'],sourceNode:nodeType,nodeClass:{'font-weight':'bold'},type:999};
                    treeObj.addNodes(selectedNode, newNode);
                }

                return true;
            } else {
                return false;
            }
        }

        //添加按键导航中的按键
        function appendNavigationKeys(keys, treeObj) {
            if (!keys) {
                return false;
            }

            $.each(keys, function (index, value) {
                if (getNodeByParamInCurrent('name', value, selectedNode, treeObj) == null) {
                    if (value == 'multiKeys') {
                        if (treeObj.getNodeByParam('condition', value, selectedNode) == null) {
                        var keyNode = {name:"{{ 'Multi keys'|trans }}",type:30,nodeClass:$red,condition:'multiKeys',parentAttr:'multi_keys_type',nodeStatus:false,icon:"{{ asset('bundles/icsocivr/images/anjian.png') }}"};
                            treeObj.addNodes(selectedNode, keyNode);
                        }
                    } else {
                        var keyNode = {name:value,type:30,nodeClass:$red,parentAttr:'navigation_keys',nodeStatus:false,icon:"{{ asset('bundles/icsocivr/images/anjian.png') }}"};
                        treeObj.addNodes(selectedNode, keyNode);
                    }
                }
            });

            //删除不选在的按键
            $.each(['1','2','3','4','5','6','7','8','9','0','8','*','multiKeys'], function (index, value) {

                if (value == 'multiKeys') {
                    var keyNode = getNodeByParamInCurrent('condition', value, selectedNode, treeObj);
                } else {
                    var keyNode = getNodeByParamInCurrent('name', value, selectedNode, treeObj);
                }

                if (keyNode != null && $.inArray(value, keys) == -1) {
                    treeObj.removeNode(keyNode);
                }
            });
            
            $.each(keys, function (index, value) {
                var keyNode = getNodeByParamInCurrent('name', value, selectedNode, treeObj);
                if (keyNode != null) {
                    treeObj.moveNode(selectedNode.children[index], keyNode, "next");
                }
            });
        }

        //添加判断节点中的按键
        function appendJudgeKeys(keys, treeObj) {
            if (!keys) {
                return false;
            }
            var  judgeNode = getNodeByParamInCurrent('type', 13, selectedNode.getParentNode(), treeObj).children;
            var judgeNodeArr = [];
            $.each(judgeNode, function (i, a) {
                judgeNodeArr.push(a.name);
            });

            $.each(keys, function (index, value) {
                if (getNodeByParamInCurrent('name', value, selectedNode, treeObj) == null) {//添加节点
                    var keyNode = {name:value,type:130,nodeClass:$red,nodeStatus:false,isDel:false,condition:'judge'+index,parentAttr:'judge',index:index,icon:"{{ asset('bundles/icsocivr/images/panduantiaojian2.png') }}"};
                    treeObj.addNodes(selectedNode, keyNode);
                }
            });


            $.each(judgeNodeArr, function (i, b) {
                if (i > 0) {
                    var node = getNodeByParamInCurrent('name', b, getNodeByParamInCurrent('type', 13, selectedNode.getParentNode(), treeObj), treeObj);
                    if (node != null && $.inArray(b, keys) == -1) {
                        treeObj.removeNode(node);
                    }
                }
            });
        }

        //添加转技能组子节点
        function appendQueueNodes(keys,treeObj)
        {
            if (!keys) {
                return false;
            }

            //无坐席节点
            var keyNode = getNodeByParamInCurrent('condition', 'none_agent', keys, treeObj);
            if (keys.if_handle_none_agent == 1) {
                if (keyNode == null) {
                    keyNode =  {name:"{{ 'None agent'|trans }}",nodeClass:$red,condition:"none_agent",type:50,parentAttr:'if_handle_none_agent',icon:"{{ asset('bundles/icsocivr/images/wuzuoxi.png') }}"};
                    treeObj.addNodes(keys, keyNode);
                }
            } else {
                if (keyNode != null) {
                    treeObj.removeNode(keyNode);
                }
            }

            //排队次数超限节点
            var keyNode = getNodeByParamInCurrent('condition', 'queue_times_exceed', keys, treeObj);
            if (keys.if_handle_queue_times_exceed == 1) {
                if (keyNode == null) {
                    keyNode =  {name:"{{ 'Queue times exceed'|trans }}",nodeClass:$red,condition:"queue_times_exceed",type:50,parentAttr:'if_handle_queue_times_exceed',icon:"{{ asset('bundles/icsocivr/images/paiduicishuchaoxian.png') }}"};
                    treeObj.addNodes(selectedNode, keyNode);
                }
            } else {
                if (keyNode != null) {
                    treeObj.removeNode(keyNode);
                }
            }

            //技能组满节点
            var keyNode = getNodeByParamInCurrent('condition', 'queue_is_full', keys, treeObj);
            if (keys.if_handle_queue_full == 1) {
                if (keyNode == null) {
                    keyNode =  {name:"{{ 'Queue is full'|trans }}",nodeClass:$red,condition:"queue_is_full",type:50,parentAttr:'if_handle_queue_full',icon:"{{ asset('bundles/icsocivr/images/jinengzuman.png') }}"};
                    treeObj.addNodes(selectedNode, keyNode);
                }
            } else {
                if (keyNode != null) {
                    treeObj.removeNode(keyNode);
                }
            }

            //排队超时节点
            var keyNode = getNodeByParamInCurrent('condition', 'queue_timeout', keys, treeObj);
            if (keys.if_handle_queue_timeout == 1) {
                if (keyNode == null) {
                    keyNode =  {name:"{{ 'Queue timeout'|trans }}",nodeClass:$red,condition:"queue_timeout",type:50,parentAttr:'if_handle_queue_timeout',icon:"{{ asset('bundles/icsocivr/images/paiduichaoshi.png') }}"};
                    treeObj.addNodes(selectedNode, keyNode);
                }
            } else {
                if (keyNode != null) {
                    treeObj.removeNode(keyNode);
                }
            }
        }

        //递归删除当前已有的节点
        function recursiveDeleteNodes(treeNode) {
            //更新父节点属性
            if (treeNode.parentAttr) {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var parentAttrNode = treeNode.getParentNode();
                switch (treeNode.parentAttr) {
                    case 'navigation_keys':
                        parentAttrNode.navigation_keys.splice($.inArray(treeNode.name,parentAttrNode.navigation_keys),1);
                        $('#form_navigation_keys').val(parentAttrNode.navigation_keys);
                        $("#form_navigation_keys").trigger("chosen:updated");
                        break;
                    case 'multi_keys_type':
                        $('#form_if_enable_multi_keys').val(0);
                        $("#form_multi_keys_start_div").addClass('hidden');
                        $("#max_keys_length_div").addClass('hidden');
                        parentAttrNode.multi_keys_type = 0;
                        break;
                    case 'if_handle_none_agent':
                        $('#form_if_handle_none_agent').val(0);
                        parentAttrNode.if_handle_none_agent = 0;
                        break;
                    case 'if_handle_queue_times_exceed':
                        $('#form_if_handle_queue_times_exceed').val(0);
                        parentAttrNode.if_handle_queue_times_exceed = 0;
                        break;
                    case 'if_handle_queue_full':
                        $('#form_if_handle_queue_full').val(0);
                        parentAttrNode.if_handle_queue_full = 0;
                        break;
                    case 'if_handle_queue_timeout':
                        $('#form_if_handle_queue_timeout').val(0);
                        parentAttrNode.if_handle_queue_timeout = 0;
                        break;
                    case 'judge':
                        parentAttrNode.conditions.splice(treeNode.index,1);
                        break;
                }

                treeObj.updateNode(parentAttrNode,treeObj);
            }

            //首先删除本身的节点
            if (treeNode.isRealNode && allNodes.hasOwnProperty(treeNode.tId)) {
                delete allNodes[treeNode.tId];
            }

            //删除该节点设置的数字变量
            delete variableName.custom[treeNode.tId];

            //判断是否包含children
            if (treeNode.children && treeNode.children.length > 0) {
                $.each(treeNode.children, function (key, child) {
                    recursiveDeleteNodes(child);
                });
            }
        }

        //递归增加当前已有的节点
        var variableTid = 1;
        function recursiveAddNodes(treeNode) {
            if (treeNode.variable_name && (treeNode.condition == 'multiKeys' || treeNode.type == 8 || treeNode.type == 9 )) {
                var vTid = variableTid
                // 去除显示时获取到http接口、收号等节点的子节点
//                if (treeNode.type == 8 || treeNode.type == 9) {
//                    vTid++;
//                }
                variableName.custom["tree_"+vTid]= treeNode.variable_name;
            }

            //首先添加本身的节点
            if (treeNode.isRealNode) {
                //var tid = 'tree_'+treeNode.name.split('-')[0];
                allNodes['tree_'+variableTid] = [];
                allNodes['tree_'+variableTid]['id'] = treeNode.name;
                allNodes['tree_'+variableTid]['nodeType'] = treeNode.type;
            }


            nodeId[treeNode.tId] = 'tree_'+variableTid;

            variableTid++;

            //判断是否包含children
            if (treeNode.children && treeNode.children.length > 0) {
                $.each(treeNode.children, function (key, child) {
                    recursiveAddNodes(child);
                });
            }
        }

        function recursiveJumpNodes(treeNode) {
            if (treeNode.jump && nodeId[treeNode.jump]) {
                treeNode.jump = nodeId[treeNode.jump];
            }
            if (treeNode.sourceNode && nodeId[treeNode.sourceNode]) {
                treeNode.sourceNode = nodeId[treeNode.sourceNode];
            }
            if (treeNode.children && treeNode.children.length > 0) {
                $.each(treeNode.children, function (key, child) {
                    recursiveJumpNodes(child);
                });
            }
            return treeNode;
        }

        /**
         * 验证语音
         *
         * @param id
         * @param type
         * @returns {boolean}
         */
        function checkt_sound(id,type)
        {
            for(var i=0;i<=id;i++) {
                if ($("#form_"+type+i).length > 0) {
                    var $sound_type = $('#form_'+type+'_sound_type'+i);
                    var $sound = $('#form_'+type+'_sound_list'+i);
                    var $sound_number = $('#form_'+type+'_sound_number'+i);
                    //验证
                    switch ($sound_type.val()) {
                        case '1'://语音列表
                            if (!$sound.val()) {
                                $sound.focus();
                                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Select Sound'|trans }}", 'error');
                                return false;
                            }
                            break;
                        case '2'://数字
                            if (!$sound_number.val()) {
                                $sound_number.focus();
                                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Input number'|trans }}", 'error');
                                return false;
                            }
                            break;
                        case '3'://数字变量
                        case '4':
                            if (!$sound_number.val()) {
                                $sound_number.focus();
                                gritterAlert("{{ 'Alert'|trans }}", "{{ 'Please Input variable name'|trans }}", 'error');
                                return false;
                            }
                            break;
                        default :
                            return false;
                            break;
                    }
                }
            }
        }

        /**
         * 保存语音
         *
         * @param id
         * @param type
         */
        function save_sound(id,type)
        {
            selectedNode[type] = [];
            var j = 0;
            for(var i=0;i<=id;i++) {
                if ($("#form_"+type+i).length > 0) {
                    //如果设置的值为空不保存
                    if ( ($('#form_'+type+'_sound_type'+i).val() == 1 && $('#form_'+type+'_sound_list'+i).val() == '') || ($('#form_'+type+'_sound_type'+i).val() == 3 && $('#form_'+type+'_sound_number'+i).val() == '')) {
                        continue;
                    }
                    selectedNode[type][j] = {};
                    selectedNode[type][j].sound_type =  $('#form_'+type+'_sound_type'+i).val();
                    selectedNode[type][j].sound_list = $('#form_'+type+'_sound_list'+i).val();
                    selectedNode[type][j].sound_number = $('#form_'+type+'_sound_number'+i).val();
                    j++;
                }
            }
        }

        /**
         * 检查变量是否存在
         *
         * @param paramValue
         */
        function checkVariableIfExist(paramValue) {
            var res = false;
//            $.each(variableName, function(index, value) {
//                if (res == true) {
//                    return false;
//                }
//                $.each(value, function(ind, val) {
//                    if (selectedNode.type == 8 || selectedNode.type == 9) {
//                        ind = parseInt(ind.replace('tree_',''));
//                        ind--;
//                        ind = 'tree_'+ind;
//                    }
//                    val = val.split(',');
//                    res = ($.inArray(paramValue, val) != -1 && selectedNode.tId != ind)  ? true : false;
//                    if (res == true) {
//                        return false;
//                    }
//                });
//            });
            return res;
        }

        /**
         * 设置变量选项
         *
         * @param $select 需要设置的表单
         */
        function setVariableOption($select)
        {
            $select.empty();
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            $select.append("<option value=''>{{ 'Please Selected Variable'|trans }}</option>");
            $.each(variableName, function(index, value) {

                switch (index) {
                    case 'system':
                        var lable = '{{ "system variable"|trans }}';
                        break;
                    case 'custom':
                        var lable = '{{ "custom variable"|trans }}';
                        break;
                    default :
                        var lable = '';
                        break;

                }

                var str = '';
                $.each(value, function(ind, val) {
                    if (index == 'system') {
                        str += "<option value='"+val+"'>"+val+"</option>";
                    } else {
                        var $node = treeObj.getNodeByTId(ind);
                        if ($.inArray(ind,allParentNode) != -1 && parseInt(ind.replace('tree_','')) <= parseInt(variableNode)) {
                            var arr = val.replace(/，/gm,',').split(',');
                            for(var i in arr){
                                str += "<option value='"+arr[i]+"'>"+$node.name+'['+arr[i]+"]</option>"
                            }
                        }
                    }
                })

                if (str) {
                    $select.append("<optgroup label='"+lable+"'></optgroup>");
                    var $optgroup = $select.find("optgroup:last");
                    $optgroup.append(str);
                }
            });
        }


        function checkAllParents(treeNode){
            if (treeNode==null || treeNode.parentTId==0) {
                return ;
            }
            else
            {
                if ($.inArray(treeNode.parentTId,allParentNode) == -1) {
                    allParentNode.push(treeNode.parentTId);
                }
                checkAllParents(treeNode.getParentNode());
            }
        }

        //检查变量名称是否合法
        function checkVariable(value)
        {
            var checkNum = /^[A-Za-z0-9_]+$/;

            return checkNum.test(value);
        }

        function checkIfnumber(value)
        {
            var checkNum = /^\d{4,12}$|^TOVCC.*$/;
            return checkNum.test(value);
        }

        //递归判断是否可以删除该节点
        function recursiveIfDeleteNodes(treeNode)
        {
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            var existNode = treeObj.getNodeByParam('sourceNode', treeNode.tId , null );

            if (existNode) {
                allParent = [];
                getAllParentNode(existNode);
                if ($.inArray(delTid,allParent) == -1) {
                    var existParentNode = existNode.getParentNode();
                    delMsg =  existParentNode.name + "{{ 'Already Exists'|trans }}" + treeNode.name;
                    return delMsg;
                }
            }

            if (delMsg=='') {
                if (treeNode.children && treeNode.children.length > 0) {
                    $.each(treeNode.children, function (key, child) {
                        recursiveIfDeleteNodes(child);
                    });
                }
            }
            return delMsg;
        }

        //获取所有父节点
        var allParent = [];
        function getAllParentNode(treeNode)
        {
            if (treeNode.parentTId != null) {
                treeNode = treeNode.getParentNode();
                allParent.push(treeNode.tId);
                getAllParentNode(treeNode);
            }

            return allParent;
        }

        //更新子节点变量
        var vars = false;
        function updateChildNodeVar(treeNode,oldVar,newVar)
        {
            var oldVarArr = oldVar.split(",");
            var newVarArr = newVar.split(",");

            if (treeNode.children && treeNode.children.length > 0) {

                $.each(treeNode.children, function (key, child) {
                    //播放语音、留言、转技能组子节点
                    if (child.type == 2 || child.type == 6 || child.type == 50 || child.type == 8) {
                        varHandleSound(child,'sound',oldVar,newVar);
                    }
                    //按键导航
                    if (child.type == 3) {
                        var varss = varHandleSound(child,'navigation_sound',oldVar,newVar);
                        if (varss) return varss;
                        var varss = varHandleSound(child,'error_key_sound',oldVar,newVar);
                        if (varss) return varss;
                        var varss = varHandleSound(child,'none_key_sound',oldVar,newVar);
                        if (varss) return varss;
                    }
                    //转技能组
                    if (child.type == 5) {
                        if (child.transfer_type == 'variable') {
                            if ($.inArray(child.variable_name,oldVarArr) != -1) {
                                if (oldVarArr.length == 1 && newVarArr.length == 1) {
                                    if (oldVarArr[0] == child.variable_name) {
                                        child.variable_name = newVarArr[0];
                                    }
                                } else {
                                    if ($.inArray(child.variable_name,oldVarArr) != -1 && $.inArray(child.variable_name,newVarArr) == -1) {
                                        vars = child.name +','+child.variable_name;
                                        return vars;
                                    }
                                }
                            }
                        }

                        var varss =varHandleSound(child,'sound',oldVar,newVar);
                        if (varss) return varss;
                        var varss = varHandleSound(child,'before_conn_sound',oldVar,newVar);
                        if (varss) return varss;
                        var varss = varHandleSound(child,'agent_side_sound',oldVar,newVar);
                        if (varss) return varss;
                    }

                    //HTTP接口、来电记忆
                    if (child.type == 9 || (child.type == 10 && child.memory_type == 3)) {
                        switch (child.type) {
                            case 9:
                                var ind = 'api_params_original';
                                break;
                            case 10:
                                var ind = 'custom_api_params';
                                break;
                        }

                        if (child[ind].length > 0) {
                            $.each(child[ind], function (key, children) {
                                if (children != null && typeof(children.params_type)!="undefined" && children.params_type == 1) {
                                    if (oldVarArr.length == 1 && newVarArr.length == 1) {
                                        if (oldVarArr[0] == children.params_value) {
                                            child[ind][key].params_value = newVarArr[0];
                                            if (child.type == 9) {
                                                child.api_params = child.api_params.replace(oldVarArr[0],newVarArr[0]);
                                            }
                                        }
                                    } else {
                                        if ($.inArray(child.variable_name,oldVarArr) != -1 && $.inArray(child.variable_name,newVarArr) == -1) {
                                            vars = child.name +','+child.variable_name;
                                            return vars;
                                        }
                                    }
                                    /*if (oldVar == children.params_value) {
                                        child.api_params_original[key].params_value = newVar;
                                    }*/
                                }
                            })
                        }
                    }

                    //转电话、转坐席
                    if (child.type == 11 || child.type == 12) {

                        if ($.inArray(child.variable_name,oldVarArr) != -1) {
                            if (oldVarArr.length == 1 && newVarArr.length == 1) {
                                if (oldVarArr[0] == child.variable_name) {
                                    child.variable_name = newVarArr[0];
                                }
                            } else {
                                if ($.inArray(child.variable_name,oldVarArr) != -1 && $.inArray(child.variable_name,newVarArr) == -1) {
                                    vars = child.name +','+child.variable_name;
                                    return vars;
                                }
                            }
                        }
                    }

                    //判断
                    if (child.type == 130 ) {
                        if (typeof(child.and)!="undefined" && child.and.length > 0) {
                            $.each(child.and, function (key, children) {
                                if (children != null && typeof(children.variable_name)!="undefined") {
                                    if (oldVarArr.length == 1 && newVarArr.length == 1) {
                                        if (oldVarArr[0] == children.variable_name) {
                                            child.and[key].variable_name = newVarArr[0];
                                        }
                                    } else {
                                        if ($.inArray(children.variable_name,oldVarArr) != -1 && $.inArray(children.variable_name,newVarArr) == -1) {
                                            vars = child.name +','+children.variable_name;
                                            return vars;
                                        }
                                    }
                                    /*if (oldVar == children.variable_name) {
                                        child.and[key].variable_name = newVar;
                                    }*/
                                }
                            })
                        }
                        if (typeof(child.or)!="undefined" && child.or.length > 0) {
                            $.each(child.or, function (key, children) {
                                if (children != null && typeof(children.variable_name)!="undefined") {
                                    if (oldVarArr.length == 1 && newVarArr.length == 1) {
                                        if (oldVarArr[0] == children.variable_name) {
                                            child.or[key].variable_name = newVarArr[0];
                                        }
                                    } else {
                                        if ($.inArray(children.variable_name,oldVarArr) != -1 && $.inArray(children.variable_name,newVarArr) == -1) {
                                            vars = child.name +','+children.variable_name;
                                            return vars;
                                        }
                                    }
                                    /*if (oldVar == children.variable_name) {
                                        child.or[key].variable_name = newVar;
                                    }*/
                                }
                            })
                        }
                    }

                    updateChildNodeVar(child,oldVar,newVar);
                });
            }


            return vars;
        }

        //处理语音相关变量
        function varHandleSound(child,type,oldVar,newVar)
        {
            var oldVarArr = oldVar.split(",");
            var newVarArr = newVar.split(",");

            if (typeof(child[type])!="undefined" && child[type].length > 0) {
                $.each(child[type], function (key, children) {
                    if (children.sound_type == 3) {
                        if (oldVarArr.length == 1 && newVarArr.length == 1) {
                            if (oldVarArr[0] == children.sound_number) {
                                child[type][key].sound_number = newVar;
                            }
                        } else {
                            if ($.inArray(children.sound_number,oldVarArr) != -1 && $.inArray(children.sound_number,newVarArr) == -1) {
                                vars = child.name +','+children.sound_number;
                                return false;
                            }
                        }
                        /*if (oldVar == children.sound_number) {
                            child[type][key].sound_number = newVar;
                        }*/
                    }
                })
            }


            return vars;
        }

        /**
         * 根据节点数据的属性在当前节点中搜索，获取条件完全匹配的节点数据 JSON 对象
         *
         * @param key
         * @param value
         * @param parendNode
         * @param treeObj
         * @returns {*}
         */
        function getNodeByParamInCurrent(key, value, parendNode, treeObj)
        {
            var currentTId = null;
            if (parendNode.children && parendNode.children.length > 0) {
                $.each(parendNode.children, function (k, child) {
                    if (child[key] == value) {
                        currentTId = child.tId;
                        return false;
                    }
                });
            }

            if (currentTId != null) {
                return treeObj.getNodeByTId(currentTId);
            } else {
                return null;
            }
        }

        function isNullObj(obj){
            for(var i in obj){
                if(obj.hasOwnProperty(i)){
                    return false;
                }
            }
            return true;
        }

        function setIvrCountName(treeNode)
        {
            if (treeNode.ivr_count_name) {
                $('#ivr_count_name').val(treeNode.ivr_count_name);
            } else {
                if (treeNode.type == 30) {
                    var name = treeNode.name == 'F' ? '按键失败' : '按键-' + treeNode.name;
                    $('#ivr_count_name').val(name);
                } else {
                    $('#ivr_count_name').val(treeNode.name);
                }
            }
            if (treeNode.hasOwnProperty("ivr_count")) {
                $('#ivr_count_id').val(treeNode.ivr_count ? 1 : 2);
            } else {
                $('#ivr_count_id').val(2);
            }
        }

        function updateSelectNodeIvrCountInfo()
        {
            selectedNode.ivr_count= $('#ivr_count_id').val() == 1 ? true : false;
            selectedNode.ivr_count_name = $.trim($('#ivr_count_name').val()).length > 0 ? $.trim($('#ivr_count_name').val()) : selectedNode.name
        }
		
		function getIvrNode(val) {
			$("#form_ivr_node").html('');
			$("#form_ivr_node").append('<option value="" selected="selected">{{ "Please Select Ivr Node"|trans }}</option>');
			$.ajax({
				url: '{{ path("icsoc_ivr_get_ivr_node") }}',
				dataType: 'json',
				data: {"ivr_code":val},
				cache: false,
				async: false,
				success: function(res){
					for (var i = 0; i < res.length; i++) {
						$("#form_ivr_node").append("<option value='"+res[i].node+"'>"+res[i].name+"</option>");
					}
				}
			});
		}
    </script>
{% endblock %}